<script setup>
import {ref, reactive, computed} from "vue";
import {businessInit, legalSendSms} from "@/api/account";
import {getCaptcha} from "@/api/login"
import {Plus} from "@element-plus/icons-vue";
import {useLoginStore} from "@/store/login.js";
import {regPhone, regIdcard} from "@zzcpt/zztool";
import {ElMessage} from "element-plus";
import {v4 as uuidv4} from "uuid";

const imgUrl = import.meta.env.VITE_BASE_API + "/business_account/business_upload_image";

const store = useLoginStore();
const time = computed(() => store.codeTime);
const submitLoading = ref(false); // 提交按钮loading
const getCodeStart = ref(false); // 获取验证码状态
const previewImgShow = ref(false); // 图片预览
const dialogImageUrl = ref();
const baseInfoFormRef = ref();
const captcha = reactive({
  session_id: "",
  captcha: "",
  loading: false
})
// const baseInfoForm = reactive({
//   business_name: 'test', // 店铺名称
//   email: "sdfdsf@163.com", // 邮箱
//   license_address: "xxxxx省", // 营业执照地址
//   license_name: "撒肯定就发考虑的就是", // 营业执照主题名称
//   license_no: "111111111111111111", // 社会统一信用代码
//   license_img: [{
//     id: "3d1e83ee-360a-4e30-b2c9-871af492fe8c",
//     url: "https://oss.hzchenjin.com/2025-03-27/business/5634ns4FdVUBDlagFVoVByFCqXEbeLzp4SJzEG0hTl6.jpg"
//   }], // 营业执照照片
//   legal_person: "懒洋洋", // 法人姓名
//   legal_person_phone: "15666666666", // 法人电话
//   legal_person_id_num: "511133197301240418", // 法人身份证号码
//   legal_person_id_img_fr: [{
//     id: "3d1e83ee-360a-4e30-b2c9-871af492fe8c",
//     url: "https://oss.hzchenjin.com/2025-03-27/business/5634ns4FdVUBDlagFVoVByFCqXEbeLzp4SJzEG0hTl6.jpg"
//   }], // 法人身份证正面照
//   legal_person_id_img_bk: [{
//     id: "3d1e83ee-360a-4e30-b2c9-871af492fe8c",
//     url: "https://oss.hzchenjin.com/2025-03-27/business/5634ns4FdVUBDlagFVoVByFCqXEbeLzp4SJzEG0hTl6.jpg"
//   }], // 法人身份证反面照
//   contract_img: [{
//     id: "3d1e83ee-360a-4e30-b2c9-871af492fe8c",
//     url: "https://oss.hzchenjin.com/2025-03-27/business/5634ns4FdVUBDlagFVoVByFCqXEbeLzp4SJzEG0hTl6.jpg"
//   }], // 合同照片
//   verify_code: "111111", // 短信验证码
//   captcha:"",
//   isGetCode: false, // 是否获取验证码
// })
const baseInfoForm = reactive({
  business_name: '', // 店铺名称
  email: "", // 邮箱
  license_address: "", // 营业执照地址
  license_name: "", // 营业执照主题名称
  license_no: "", // 社会统一信用代码
  license_img: [], // 营业执照照片
  legal_person: "", // 法人姓名
  legal_person_phone: "", // 法人电话
  legal_person_id_num: "", // 法人身份证号码
  legal_person_id_img_fr: [], // 法人身份证正面照
  legal_person_id_img_bk: [], // 法人身份证反面照
  contract_img: [], // 合同照片
  verify_code: "", // 短信验证码
  captcha:"",
  isGetCode: false, // 是否获取验证码
})
const checkPhone = (rule, value, callback) => {
  if (!regPhone(value)) {
    callback(new Error('请输入正确的手机号码'));
  } else {
    callback();
  }
}
const checkIdCard = (rule, value, callback) => {
  if (!regIdcard(value)) {
    callback(new Error('请输入正确的身份证号码'));
  } else {
    callback();
  }
}
const baseInfoFormRule = {
  business_name: [
    {required: true, message: "请输入店铺名称", trigger: "blur"},
    {min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur"}
  ],
  email: [
    {required: true, message: "请输入邮箱地址", trigger: "blur"},
    {type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"]}
  ],
  license_address: [
    {required: true, message: "请输入营业执照地址", trigger: "blur"},
  ],
  license_name: [
    {required: true, message: "请输入营业执照主题名称", trigger: "blur"}
  ],
  license_no: [
    {required: true, message: "请输入社会统一信用代码", trigger: "blur"},
    {min: 18, max: 18, message: "长度必须为18位", trigger: "blur"}
  ],
  license_img: [
    {required: true, message: "请上传营业执照照片", trigger: "blur"}
  ],
  legal_person: [
    {required: true, message: "请输入法人姓名", trigger: "blur"}
  ],
  legal_person_phone: [
    {required: true, message: "请输入法人电话", trigger: "blur"},
    {validator: checkPhone, trigger: "blur"}
  ],
  legal_person_id_num: [
    {required: true, message: "请输入法人身份证号码", trigger: "blur"},
    {validator: checkIdCard, trigger: "blur"}
  ],
  legal_person_id_img_fr: [
    {required: true, message: "请上传法人身份证正面照", trigger: "blur"}
  ],
  legal_person_id_img_bk: [
    {required: true, message: "请上传法人身份证反面照", trigger: "blur"}
  ],
  contract_img: [
    {required: true, message: "请上传合同照片", trigger: "blur"}
  ],
  verify_code: [
    {required: true, message: "请输入短信验证码", trigger: "blur"},
  ],
  captcha: [
    {required: true, message: "请输入图形验证码", trigger: "blur"},
  ]
  
}


const handleRemove = (uploadFile, uploadFiles) => {
};
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  previewImgShow.value = true;
};
const handleSuccess = (response, uploadFile) => {
};

async function getCode() {
  if (getCodeStart.value) return;
  if (baseInfoForm.isGetCode) {
    ElMessage.info("发送中")
    return;
  }
  if(!baseInfoForm.captcha){
    ElMessage.error("请输入图形验证码");
    return
  }
  if(!regPhone(baseInfoForm.legal_person_phone)){
    ElMessage.error("请输入正确的手机号码");
    return
  }
  baseInfoForm.isGetCode = true;
  try {
    await legalSendSms({
      phone: baseInfoForm.legal_person_phone,
      session_id: captcha.session_id,
      captcha: baseInfoForm.captcha,
    })
    ElMessage.success("验证码发送成功");
    getCodeStart.value = true;
    store.startCodeTime();
    setTimeout(() => {
      getCodeStart.value = false;
    }, 60000);
  }catch (e) {
    console.error(e)
  }finally {
    baseInfoForm.isGetCode = false;
  }
}
function resetCaptcha(){
  captcha.session_id = '';
  captcha.captcha = '';
  captcha.loading = false
}
getCaptchaFn()
async function getCaptchaFn() {
  resetCaptcha()
  captcha.loading = true;
  await getCaptcha().then((res) => {
    captcha.session_id = res.data.session_id;
    captcha.captcha = res.data.captcha;
    captcha.loading = false
  });
}

async function submitForm() {
  const valid = await baseInfoFormRef.value.validate();
  console.log(valid)
  if (!valid) {
    ElMessage.error("请完善信息");
    return;
  }
  
  const getImageParam = (data) => {
    return data.map(item => {
      return {
        id: uuidv4(),
        url: item?.response ? item.response.data : item.url
      };
    })
  }
  const param = {
    business_name: baseInfoForm.business_name, // 店铺名称
    email: baseInfoForm.email,
    license_address: baseInfoForm.license_address,
    license_name: baseInfoForm.license_name,
    license_no: baseInfoForm.license_no,
    license_img: JSON.stringify(getImageParam(baseInfoForm.license_img)),
    legal_person: baseInfoForm.legal_person,
    legal_person_phone: baseInfoForm.legal_person_phone,
    legal_person_id_num: baseInfoForm.legal_person_id_num,
    legal_person_id_img_fr: JSON.stringify(getImageParam(baseInfoForm.legal_person_id_img_fr)),
    legal_person_id_img_bk: JSON.stringify(getImageParam(baseInfoForm.legal_person_id_img_bk)),
    contract_img: JSON.stringify(getImageParam(baseInfoForm.contract_img)),
    verify_code: baseInfoForm.verify_code,
  }
  try {
    submitLoading.value = true;
    const res = await businessInit(param);
    if (res.code === 200) {
      ElMessage.success(res.msg);
    }
  }catch (e) {
    console.error(e)
  }finally {
    submitLoading.value = false
  }
}
</script>
<template>
  <div class="container">
    <div class="title">xxxx</div>
    <div class="box">
      <el-form
        ref="baseInfoFormRef"
        :model="baseInfoForm"
        :rules="baseInfoFormRule"
        label-width="auto"
        status-icon
      >
        <el-form-item label="账号名称" prop="business_name">
          <el-input v-model="baseInfoForm.business_name"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="baseInfoForm.email"/>
        </el-form-item>
        <el-form-item label="营业执照地址" prop="license_address">
          <el-input v-model="baseInfoForm.license_address"/>
        </el-form-item>
        <el-form-item label="营业执照主体名称" prop="license_name">
          <el-input v-model="baseInfoForm.license_name"/>
        </el-form-item>
        <el-form-item label="社会统一信用代码" prop="license_no">
          <el-input v-model="baseInfoForm.license_no"/>
        </el-form-item>
        <el-form-item label="营业执照照片" prop="license_img">
          <el-upload
            v-model:file-list="baseInfoForm.license_img"
            :action="imgUrl"
            :on-success="handleSuccess"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            accept="image/*"
            :limit="1"
          >
            <el-icon>
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="法人姓名" prop="legal_person">
          <el-input v-model="baseInfoForm.legal_person"/>
        </el-form-item>
        <el-form-item label="法人电话" prop="legal_person_phone">
          <el-input v-model="baseInfoForm.legal_person_phone"/>
        </el-form-item>
        <el-form-item label="法人身份证号码" prop="legal_person_id_num">
          <el-input v-model="baseInfoForm.legal_person_id_num"/>
        </el-form-item>
        <el-form-item label="法人身份证正面照" prop="legal_person_id_img_fr">
          <el-upload
            v-model:file-list="baseInfoForm.legal_person_id_img_fr"
            :action="imgUrl"
            :on-success="handleSuccess"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            accept="image/*"
            :limit="1"
          >
            <el-icon>
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="法人身份证反面照" prop="legal_person_id_img_bk">
          <el-upload
            v-model:file-list="baseInfoForm.legal_person_id_img_bk"
            :action="imgUrl"
            :on-success="handleSuccess"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            accept="image/*"
            :limit="1"
          >
            <el-icon>
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="合同照片" prop="contract_img">
          <el-upload
            v-model:file-list="baseInfoForm.contract_img"
            :action="imgUrl"
            :on-success="handleSuccess"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            accept="image/*"
            :limit="1"
          >
            <el-icon>
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="图形验证码" prop="captcha">
          <el-input v-model="baseInfoForm.captcha">
            <template #append>
              <el-image @click="getCaptchaFn" class="pointer h-full" v-loading="captcha.loading"
                        :src="captcha.captcha"></el-image>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="短信验证码" prop="verify_code">
          <el-input v-model="baseInfoForm.verify_code">
            <template #append>
              <span class="pointer" style="color: #000" @click="getCode()">
                {{ getCodeStart ? time : "获取验证码" }}
              </span>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
    </div>
    <div class="box mt-1">
      <el-button :loading="submitLoading" @click="submitForm" type="primary">提交</el-button>
    </div>
    <el-dialog v-model="previewImgShow">
      <el-image style="width: 100%; height: auto" :src="dialogImageUrl" fit="fill"/>
    </el-dialog>
  </div>
</template>


